<?php
namespace api\modules\v1\controllers\goods;

use api\controllers\OnAuthController;
use api\modules\v1\models\ModuleJd;
use api\modules\v1\models\ModuleSuperior;
use common\enums\StatusEnum;
use common\models\shop\ShopActivity;
use phpDocumentor\Reflection\Types\Integer;
use Yii;
use yii\web\NotFoundHttpException;

class JDController extends OnAuthController
{
    public $modelClass = 'common\models\goods\GoodsCommon';

    protected $client = null;
    protected $app_key = '8b32b870a164fa1825891c3438b590c5';
    protected $app_secret = 'f11ffc93a3b549d08fb761ba8b119b97';

    protected $page_size = '20';

    public $optional = ['promotion-common','goods-info','order-bonus','order','activity','promotion-goods-info','goods-jingfen','category-goods','category','setting','goods','goods-seckill','goods-stuprice','goods-bigfield'];

    /**
     * 获取通用推广链接
     * @return bool|mixed|string
     * @throws NotFoundHttpException
     */
    public function actionPromotionCommon(){
        $request = \Yii::$app->request;
        $member_id = $this->getUser();

        return ModuleJd::promotionCommon($request,$member_id);
    }

    /**
     * 奖励订单查询接口
     * @return bool|mixed|string
     * @throws NotFoundHttpException
     */
    public function actionOrderBonus(){
        $request = \Yii::$app->request;
        return ModuleJd::orderBonus($request);
    }

    /**
     * 订单查询
     * @return bool|mixed|string
     * @throws NotFoundHttpException
     */
    public function actionOrder(){
        $request = \Yii::$app->request;
        return ModuleJd::order($request);
    }

    /**
     * 获取配置
     * @return array
     */
    public function actionSetting(){
        $data = [
            'subsidy_ratio' => 0.5,//补贴
        ];
        return $data;
    }

    /**
     * 获取分类
     * @return array
     */
    public function actionCategory(){
        $data = [
            [
                'title'=>'母婴',
                'id'=>1319
            ],
            [
                'title'=>'食品饮料',
                'id'=>1320
            ],
            [
                'title'=>'服饰内衣',
                'id'=>1315
            ],
            [
                'title'=>'箱包皮具',
                'id'=>17329
            ],
            [
                'title'=>'美妆护肤',
                'id'=>1316
            ],
            [
                'title'=>'个人护理',
                'id'=>16750
            ],
            [
                'title'=>'家用电器',
                'id'=>737
            ]
        ];
        return $data;
    }

    /**
     * 所有分类
     * @return bool|mixed|string
     */
    public function actionCategoryGoods(){
        $request = \Yii::$app->request;
        return ModuleJd::categoryAll($request);
    }

    /**
     * 活动列表
     * @return array
     */
    public function actionActivity(){
        $cache = Yii::$app->cache;
        $data = $cache->get('shop-activity');
        if(!$data){
            $data = ShopActivity::find()->where([">",'status',StatusEnum::DELETE])->orderBy(['sort'=>SORT_DESC])->asArray()->all();
            $cache->set('shop-activity',$data);
        }
        return $data;
    }

    /**
     * 获取登录用户信息
     * @return |null
     */
    protected function getUser(){
        if(Yii::$app->user->identity){
            $member_id = Yii::$app->user->identity->member_id;
            return $member_id;
        }else return null;
    }

    /**
     * 获取商品详情
     * @return mixed
     */
    public function actionGoodsInfo(){
        $request = \Yii::$app->request;
        $id = $request->get('id','');
        $goods = self::getJDCache('jd-goods',[$id]);
        if(!$goods){
            $result = ModuleJd::promotionGoodsInfo(['skuIds'=>$id]);
            $goods2 = $result[0];
        }else $goods2 = null;
        return ['goods'=>$goods,'goods2'=>$goods2];
    }

    /**
     * 京粉精选商品查询接口
     * @param Integer|eliteId 频道id：1-好券商品,2-超级大卖场,10-9.9专区,22-热销爆品,24-数码家电,25-超市,26-母婴玩具,27-家具日用,28-美妆穿搭,29-医药保健,30-图书文具,31-今日必推,32-王牌好货,33-秒杀商品,34-拼购商品
     * @param Integer|pageIndex
     * @param Integer|pageSize
     * @param String|sortName
     * @param String|sorts
     * @return bool|mixed
     */
    public function actionGoodsJingfen(){
        $request = \Yii::$app->request;
        $member_id = $this->getUser();

        $jd_data = ModuleJd::goodsJingfen($request);
        //处理用户数据
        foreach ($jd_data as $k=>$v){
            ModuleSuperior::getUserJDData($jd_data[$k], $member_id);
        }
        return $jd_data;
    }

    /**
     * 关键词商品查询接口
     * @return bool
     */
    public function actionGoods(){
        $request = \Yii::$app->request;
        return ModuleJd::goodsSearch($request);
    }

    /**
     * 获取推广商品信息接口
     * @return array|bool|mixed|string
     */
    public function actionPromotionGoodsInfo(){
        $request = \Yii::$app->request;
        return ModuleJd::promotionGoodsInfo($request);
    }


    /**
     * 秒杀
     * @return bool|mixed|string
     */
    public function actionGoodsSeckill(){
        $request = \Yii::$app->request;
        return ModuleJd::goodsSeckill($request);
    }

    /**
     * 学生价商品查询接口
     * @return bool
     * @throws NotFoundHttpException
     */
    public function actionGoodsStuprice(){
        $request = \Yii::$app->request;
        return ModuleJd::goodsStuprice($request);
    }

    /**
     * 大字段商品查询接口
     * @return bool
     * @throws NotFoundHttpException
     */
    public function actionGoodsBigfield(){
        $request = \Yii::$app->request;
        return ModuleJd::goodsBigfield($request);
    }


    /**
     * 获取京东数据缓存
     * @param $key
     * @param $params
     * @return mixed
     */
    protected function getJDCache($key, $params){
        $cache = Yii::$app->cache;
        unset($params['access-token']);
        $redis_key = $key . '-' . implode('-',$params);
        return $cache->get($redis_key);
    }

    /**
     * 保存京东数据缓存
     * @param $key
     * @param $params
     * @param $data
     * @param int $expire
     */
    protected function setJDCache($key, $params, $data, $expire = 86400){
        $cache = Yii::$app->cache;
        unset($params['access-token']);
        $redis_key = $key . '-' . implode('-',$params);
        return $cache->set($redis_key, $data, $expire);
    }


    // post请求
    protected function curl_post($url, $curlPost)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_REFERER, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
    protected function sign_method($method,$data=array()){
        date_default_timezone_set("PRC");
        $sign_method = array(
            'app_key'=> $this->app_key,
            'timestamp'=> date('Y-m-d H:i:s'),
            'format' => 'json',
            'method' => $method,
            'v' => '1.0',
            'sign_method'=>'md5',
        );
        $sign_method = array_merge($sign_method,$data);
        ksort($sign_method);
        // var_dump($array_merge);die();
        $data = $this->app_secret;
        foreach ($sign_method as $key => $value) {
            $data .= trim($key) .trim($value);
        }
        $data .= $this->app_secret;
        $sign_method['sign'] = strtoupper(md5($data));
        // echo "<pre>";
        // var_dump($sign_method);die();
        return $sign_method;
    }
}